<script setup>
import { use } from 'echarts/core'
import { TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import 'echarts-wordcloud' // 导入词云扩展
import { ref, watch } from 'vue'

// 注册必要的组件
use([TitleComponent, CanvasRenderer])

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '400px'
  }
})

const option = ref({
  title: {
    text: props.title,
    left: 'center'
  },
  series: [{
    type: 'wordCloud',
    shape: 'circle',
    left: 'center',
    top: 'center',
    width: '90%',
    height: '90%',
    right: null,
    bottom: null,
    sizeRange: [12, 60],
    rotationRange: [-90, 90],
    rotationStep: 45,
    gridSize: 8,
    drawOutOfBound: false,
    textStyle: {
      fontFamily: 'sans-serif',
      fontWeight: 'bold',
      color: function () {
        return 'rgb(' + [
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160)
        ].join(',') + ')'
      }
    },
    emphasis: {
      focus: 'self',
      textStyle: {
        shadowBlur: 10,
        shadowColor: '#333'
      }
    },
    data: props.data
  }]
})

watch(() => props.data, (newVal) => {
  option.value.series[0].data = newVal
}, { deep: true })

watch(() => props.title, (newVal) => {
  option.value.title.text = newVal
})
</script>

<template>
  <v-chart class="chart" :option="option" :style="{ height }" />
</template>

<style scoped>
.chart {
  width: 100%;
}
</style>